package com.etlmaster.executor.steps.control;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import com.etlmaster.executor.utils.DpVfsUtils;
import com.etlmaster.executor.utils.StepState;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class AssignFileProcessor extends AssignProcessor {

	@Override
	public int process(AssignStepMeta meta) {
		if (expression.indexOf(" open ") > 0) {
			int posi = expression.indexOf(" open ");
			String variableName = expression.substring(0, posi);
			String sqlStatement = expression.substring(posi + 6,
					expression.length());

			FileObject fileObject = DpVfsUtils.getInstance().resolveFile(
					sqlStatement);
			try {
				if (!fileObject.exists()) {
					meta.log("ERROR","文件不存在，{}", sqlStatement);
					return StepState.RUNNING_FAILED;
				}

				if (fileObject.getType() == FileType.FILE) {
					InputStream in = fileObject.getContent().getInputStream();

					try {
						List<String> data = IOUtils.readLines(in);
						meta.getStepState().getReturnValue()
								.put(variableName, data);
					} catch (IOException e) {
						meta.log("ERROR","读取文件异常：{}",e.getMessage());
						return StepState.RUNNING_FAILED;
					} finally {
						try {
							in.close();
						} catch (IOException e) {
							meta.log("ERROR","关闭输入流异常：{}",e.getMessage());
							return StepState.RUNNING_FAILED;
						}
						DpVfsUtils.getInstance().closeFileObject(fileObject);
					}
				}
			} catch (FileSystemException e) {
				meta.log("ERROR","文件异常：{}",e.getMessage());
				return StepState.RUNNING_FAILED;
			}
		}
		return StepState.RUNNING_SUCCESSED;
	}

}
